const path = require('path')

const log = require('../log/log.js')
const error = require('../error/error.js')
const config = require('../config/index.js')
const string = require('./string.js')

const uniID = require(path.resolve(__dirname, '../../uni-id/index.js'))

const commonUtils = {
  // 解析入参
  solveParams (event) {
    let params = {}
    if (event.httpMethod) {
      // 云函数URL化
      if (event.httpMethod === 'GET') {
        params = event.queryStringParameters
      }
      else {
        params = event.body
      }
    }
    else {
      // 云函数普通调用
      params = event
    }
    
    log.log(params, '接收到的参数')
    return params
  },
  
  // 检查token
  async checkToken (action, token, params = {}) {
    const noCkeckActions = config.common.noCheckActions
    
    if (noCkeckActions.indexOf(action) < 0) {
      if (!token) {
        // 不合法的token
        return error('TOKEN_ERROR')
      }
      payload = await uniID.checkToken(token)
      if (payload.code && payload.code > 0) {
        // token校验不通过
        return Promise.reject(payload)
      }
      
      // token检验通过，会给参数带上对应的uid字段
      if (params && typeof params === 'object') {
        params.uid = payload.uid
      }
      return payload
    }
  },
  
  // 出参转化为xml
  outXml (data = {}, key = '', layer = 0, result = '') {
    if (typeof data !== 'object') {
      // 数据不是对象时
      result = result + string.gap(layer * 2) + `<${key}>${data.toString()}</${key}>`
      if (layer > 0) {
        result = result + '\n'
      }
      return result
    }
    
    // 数据时对象时
    // 标签头部
    result = result + string.gap(layer * 2) +  `<${key}>\n`
    
    for (let key in data) {
      result = commonUtils.outXml(data[key], key, layer + 1, result)      
    }
    
    // 闭合标签
    result = result + string.gap(layer * 2) + `</${key}>`
    if (layer > 0) {
      result = result + '\n'
    }
    
    return result
  }
}

module.exports = commonUtils